package com.woniuxy.portal.config.rabbitmq;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMQConfig {

    @Bean
    public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        // 开启消息的强制投递
        rabbitTemplate.setMandatory(true);

        // 消息到达交换机的确认
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                System.out.println("消息数据 = " + correlationData);
                if (ack) {
                    System.out.println("消息到达了交换机");
                } else {
                    System.out.println("消息未到达交换机: " + cause);
                }
            }
        });

        // 消息回退的回调函数
        rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
            // 什么时候触发？ 消息从交换机正常路由到队列，不触发； 消息到家交换，且无法路由到队列，触发
            @Override
            public void returnedMessage(
                    Message message, int replyCode, String replyText, String exchange, String routingKey) {
                // 保存发送失败的消息，入库....
                System.out.println("消息内容 = " + message);
                System.out.println("响应编码 = " + replyCode);
                System.out.println("交换机 = " + exchange);
                System.out.println("路由key = " + routingKey);
            }
        });

        return rabbitTemplate;
    }
}
